<template>
  <q-card class="full-height">
    <q-table flat bordered virtual-scroll :pagination="pagination" :rows-per-page-options="rowsPerPageOptions"
             :loading="loading" :rows="applicants" :columns="columns" row-key="jobSeekerId" class="full-height" card-class="bg-primary" table-class="bg-white">
      <template v-slot:top>
        <q-banner class="bg-primary q-pa-none q-ma-none text-white full-width">
          <div class="row justify-between">
            <span class="applicant-list-title col-6 text-left row full-height self-center">申请人列表</span>
          </div>
        </q-banner>
      </template>
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            <div class="full-width text-left text-weight-bold">{{ col.label }}</div>
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td v-for="col in props.cols" :key="col.name" :props="props">
            <div v-if="col.name == 'action'" class="text-left">
              <q-btn-group>
                <q-btn dense label="查看简历" @click="showResume(props.row)"/>
                <q-btn v-if="props.row.description" dense label="分析报告" @click="showAnalysisReport(props.row)"/>
              </q-btn-group>
            </div>
            <div v-else class="text-left">
              {{ col?.format ? col.format(props.row[col.name], props.row) : props.row[col.name]}}
            </div>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:no-data>
        <span class="text-white" style="font-size: 14px"><q-icon name="warning" class="q-mx-xs" size="20px"/>找不到数据</span>
      </template>
      <template v-slot:bottom>
        <div class="flex flex-center full-width full-height text-white">
          <q-select dense options-dense v-model="pagination.rowsPerPage" :options="rowsPerPageOptions" bg-color="white"
                    transition-show="jump-up" transition-hide="jump-up" @update:model-value="loadApplicants">
            <template v-slot:after>
              <span class="select-text">条/页 共{{ pagination.rowsNumber }}条数据</span>
            </template>
          </q-select>
          <q-pagination
              v-model="pagination.page" :max="pages" :max-pages="3"
              ellipsess boundary-numbers :direction-links="true"
              @update:model-value="changePagination"
              @input="changePagination" active-text-color="black"
              color="white"
          >
          </q-pagination>
          <span>跳至</span>
          <q-input dense outlined
                   v-model="toPage"
                   class="text-black text-weight-bolder bg-white rounded-borders q-mx-xs"
                   @input="changeToPage" @keyup.enter.native="refreshTableData"
          ></q-input>
          <span>页</span>
        </div>
      </template>
    </q-table>
  </q-card>
  <q-dialog v-model="showAnalysisDetail">
    <q-card>
      <q-card-section>
        {{analysisDetail}}
      </q-card-section>
    </q-card>
  </q-dialog>
</template>
<style scoped lang="sass">
.applicant-list-title
  font-size: 24px
  font-weight: bolder
.content-overflow-hidden
  white-space: nowrap
  overflow: hidden
  text-overflow: ellipsis
.job-detail
  height: 91vh
  .requirements
    font-size: 16px
    font-weight: bolder
  .description
    border: 1px solid #ccc
    border-radius: 10px
    height: 78vh
    white-space: pre-wrap
    font-size: 16px
    overflow: scroll
.select-text
  font-size: 12px
  color: white
</style>
<script setup lang="ts">
import type {Applicant, JobPost, Pagination} from "../vite-env.d";
import {getCurrentInstance, onMounted, ref, watch} from "vue";
import RecruiterService from "../services/RecruiterService.ts";
import {LocalStorageUtil} from "../assets/local-storage";
import {RECRUITER_ROLE} from "../vite-env.d";
import {HttpService} from "../assets/Http";

const props = defineProps({
  jobPost: Object as JobPost
})
watch(() => props.jobPost, async () => {
  await loadApplicants()
})
const showAnalysisDetail = ref(false)
const analysisDetail = ref<string | null>(null)
const instance = getCurrentInstance()
const recruiterService = new RecruiterService()
const applicants = ref<Applicant[]>([])
const rowsPerPageOptions = [10, 20, 50, 100]
const loading = ref(false)
const pages = ref(1)
const toPage = ref('')
const pagination = ref<Pagination>( {
  sortBy: 'score',
  descending: true,
  page: 1,
  rowsPerPage: rowsPerPageOptions[0],
  rowsNumber: 22
})
const columns = [
  {name: "job_seeker_id", require: true, label: "ID"},
  {name: "job_seeker_name", require: true, label: "申请人"},
  {name: "resume_name", require: true, label: "简历名称"},
  {name: "match_rate", require: true, label: "匹配度"},
  {name: "status", require: true, label: "分析状态", format: (val, row) => {
    const statusMap = new Map()
    statusMap.set(0, "未执行")
    statusMap.set(1, "正在执行")
    statusMap.set(2, "已完成")
    return statusMap.get(val)
  }},
  {name: "action", require: true, label: "操作"},
]
onMounted(async () => {
  await loadApplicants()
})
const changePagination = async (page: number) => {
  await getApplicantPages(page)
}
const changeToPage = async (val: string) => {
  let r = /^\+?[1-9][0-9]*$/
  if (r.test(val) && parseInt(val) <= pages.value) {
    // 输入正整数 且 小于最大页数
    // console.log(`input toPage: ${val} 是一个正整数`)
    await getApplicantPages(parseInt(val))
  } else {
    toPage.value = ''
  }
}

const refreshTableData = async () => {
  if (toPage.value !== '') {
    pagination.value.page = parseInt(toPage.value)
    await getApplicantPages()
  }
}
const getApplicantPages = async (page: number = 1, rowsPerPage: number = pagination.value.rowsPerPage) => {
  const proxy = instance?.proxy
  if (!proxy.jobPost)
    return
  loading.value = true
  console.log("applicantPagination", proxy.jobPost.id,  page, rowsPerPage)
  const {type, user} = await LocalStorageUtil.getCurrentUser()
  if (type == RECRUITER_ROLE && user) {
    const applicantPagination = await recruiterService.getApplicantPages(user.id, proxy.jobPost.id,page - 1, rowsPerPage)
    if (applicantPagination?.data)
      applicants.value = applicantPagination.data
    pagination.value.page = page
    pagination.value.rowsPerPage = applicantPagination.rowsPerPage
    pagination.value.rowsNumber = applicantPagination.rowsNumber
    pagination.value.descending = applicantPagination.descending
    pagination.value.sortBy = applicantPagination.sortBy
    pages.value = Math.ceil(applicantPagination.rowsNumber/applicantPagination.rowsPerPage)
    loading.value = false
  }
}
const loadApplicants = async () => {
  return getApplicantPages()
}
const showResume = async (applicant: Applicant) => {
  HttpService.openFile("/jobSeeker/downloadResume", {
    job_seeker_id: applicant.job_seeker_id,
    resume_id: applicant.resume_id
  })
}
const showAnalysisReport = async (applicant: Applicant) => {
  showAnalysisDetail.value = true;
  analysisDetail.value = applicant.description
}
</script>
